GoLang

Explain Constants in Go Programming Language | Go Programming Tutorial

Explain Constants in Go Programming Language | Go Programming Tutorial

Explain Constants in Go Programming Language | Go Programming Tutorial

In this article, you will learn:

  • What are constants?
  • How to declare the constants?
  • Types of constants

What are constants?

In simple layman's language, constants mean fixed. Once the value of constants is defined, it can not be altered. Constants can be of any basic data type such as integer constant, floating constant, character constant, or string literals.

How to declare the constants?

Constants are declared as normal variables but the only difference is it uses the const keyword as a prefix before declaring a constant of a specific data type.

Types of constants:

  • Typed Numeric constants: Types constants are immutable variables that can be inter-operate only with the same data type. 
  • UnTyped Numeric constants: UnTyped Numeric constants are considered a literal that can be inter-operated with similar types.

Note: Constants in the Go language can be declared with or without a type in Go.

List of constants in Go Language:

  • Numeric constants include Integer constants, Floating point constants, and complex constants.
  • String Literals
  • Boolean constants

Numeric Constants: These are high-precision values. As Go Programming language is statically typed language it does not mix with other numeric types. 

Numeric constants can be of 3 kinds:

  • Integer 
  • Floating-point
  • Complex

Integer constant:

  • It can be a decimal, octal, or hexadecimal constant.
  • An int can store the maximum of a 64-bit integer, and sometimes less also.

Floating-Point constant:

  • A floating-point constant has an integer part along with a decimal part.
  • It can be represented as a floating constant either in exponential or decimal form.
  • The exponential form must include the integer part, the fractional part, or both.

Complex constant:

It behaves similarly to floating point constants. It has both a real pair of integer constants and an imaginary part.

String Literals:

  • Go supports two types of string literal i.e double-quote style and back-quote.
  • It can be concatenated with + and += operators.
  • The string can be compared by using the operators like ==, != and literal.

Boolean constant: 

Boolean constants are much similar to string constants. It has the same rules as a string constant. It has only two untyped constants true and false.

Yamini  Sharma

I am working as a professional engineer in "HIghRadius Technologies Pvt. Ltd." Passionate about learning and exploring new technologies. Enthusiast in writing and sharing what I have in my knowledge bucket.